<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\Category;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class CategoryController extends CommonController
{
	//get admin/category
	public function index()
	{
		$categories = (new Category)->tree();
		return view('admin.category.index')->with('data', $categories);
    }

	//get admin/category/create
	public function create()
	{
		$categories = Category::where('cate_pid', 0)->get();
		return view('admin/category/create', compact('categories'));
	}

	//post admin/category  负责添加分类后的存储
	public function store()
	{
		$input = Input::except('_token');
		$rules = [
			'cate_name' => 'required',
		];
		$message = [
			'cate_name.required' => '分类名称不能为空',
		];
		$validator = Validator::make($input, $rules, $message);

		if ($validator->passes()) {
			$result = Category::create($input);
			if ($result) {
				return redirect('admin/category');
			} else {
				return back()->with('errors', '数据添加失败，请稍后重试');
			}

		} else {
			return back()->withErrors($validator);
		}
	}

	//put admin/category/{category}
	public function update($cate_id)
	{
		$input = Input::except('_token', '_method');
		$result = Category::where('cate_id', $cate_id)->update($input);
		if ($result) {
			return redirect('admin/category');
		} else {
			return back()->with('errors', '分类信息更新失败，请稍后重试');
		}
	}

	//get admin/category/{category}/edit
	public function edit($cate_id)
	{
		$field = Category::find($cate_id);
		$categories = Category::where('cate_pid', 0)->get();
		return view('admin.category.edit', compact('field', 'categories'));
	}
	//get admin/category/{category}
	public function show($cate_id)
	{

	}

	//delete admin/category/{category}
	public function destroy($cate_id)
	{
		$result = Category::where('cate_id', $cate_id)->delete();
		//如果删除的是顶级分类，那么将其子分类升级为顶级分类
		Category::where('cate_pid', $cate_id)->update(['cate_pid' => 0]);
		if ($result) {
			$data = [
				'status' => 0,
				'msg' => '分类删除成功'
			];
		} else {
			$data = [
				'status' => 1,
				'msg' => '分类删除失败'
			];
		}
		return $data;
	}

	public function changeOrder()
	{
		$input = Input::all();
		$cate = Category::find($input['cate_id']);
		$cate->cate_order = $input['cate_order'];
		$result = $cate->update();
		if($result) {
			$data = [
				'status' => 0,
				'msg' => '分类排序更新成功',
			];
		} else {
			$data = [
				'status' => 1,
				'msg' => '分类排序更新失败，请稍后重试',
			];
		}
		return $data;
	}
}
